using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace EventBehaviorTree
{
    public class StateSwitcher : Container
    {
        private bool _isSubNodeWorking;
        public StateSwitcher(KeyValuePair<NodeMsg, NodeMsg>[] messagePairs, params NodeMsg[] silencedMessage) :
            base(messagePairs, silencedMessage)
        { }
        public StateSwitcher() : base() { }

        protected override IEnumerator Worker()
        {
            while (_isWorking && (!_isSubNodeWorking))
            {
                yield return null;
                NodeEvent(NodeMsg.Start);
            }
            _asyncWorker.ResetWorker(Worker());
        }

        public override void NodeEvent(NodeMsg nodeMessage)
        {
            switch (nodeMessage)
            {
                case NodeMsg.Start:
                    if (!_isWorking) SendMessage(nodeMessage);
                    _isWorking = true;
                    _stepCount = 0;
                    _isSubNodeWorking = true;//transform to false when failed or abort
                    _subNodes[0].NodeEvent(nodeMessage);
                    break;
                case NodeMsg.Succeed:
                    _isSubNodeWorking = true;
                    //SendMessage(nodeMessage);
                    break;
                case NodeMsg.Fail:
                    if (_stepCount < _subNodes.Count - 1)
                    {
                        _subNodes[++_stepCount].NodeEvent(NodeMsg.Start);
                        return;
                    }
                    _isSubNodeWorking = false;
                    StartWithEnumerator();//all failed, start watcher
                    //SendMessage(nodeMessage);
                    break;
                case NodeMsg.REQ_Abort://get the request from sub node
                    _isSubNodeWorking = false;
                    NodeEvent(NodeMsg.Start);//check once in this frame
                    //SendMessage(nodeMessage);
                    break;
                case NodeMsg.CMD_Stop:
                    if (_isWorking)
                    {
                        StopWithEnumerator();
                        _isSubNodeWorking = false;
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
